<template>
  <div class="chat-countdown-timer" :style="{ '--bgColor': bgColor, '--fontColor': fontColor }">
    <div class="dot">{{ title }}</div>
    <div>剩余：{{ countdown }}</div>
  </div>
</template>
<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted, onBeforeUnmount } from '../../../adapter-vue'

const props = defineProps({
  title: {
    type: String,
    default: () => 'Title',
  },
  startTime: {
    type: Number,
    default: () => 1720147331210,
  },
  endTime: {
    type: Number,
    default: () => 1720149391210,
  },
  nowTime: {
    type: Number,
    default: () => Date.now(),
  },
  fontColor: {
    type: String,
    default: () => '#1ec06f',
  },
  bgColor: {
    type: String,
    default: () => 'rgba(220,251,235,0.6)',
  },
})

// 定时器ID
const countdown = ref<string>('00:00:00')
let timerId: any = null

/**
 * 启动倒计时
 * @param startTime 开始时间(单位为时间戳)
 * @param endTime 结束时间(单位为时间戳)
 */
function startCountdown(startTime: number, endTime: number) {
  // 判断开始时间是否大于结束时间
  if (endTime <= startTime) {
    console.log('开始时间不能大于等于结束时间！')
    return
  }

  // 计算时间差，单位为毫秒
  let diff = Math.abs(startTime - endTime)
  // 将毫秒转换为秒
  let diffInSeconds = Math.floor(diff / 1000)

  // 更新倒计时显示
  function updateCountdown() {
    if (diffInSeconds < 0) {
      console.log('倒计时结束！')
      return
    }

    // 计算小时、分钟和秒
    let day = Math.floor(diffInSeconds / 3600 / 24)
    let hours = Math.floor(diffInSeconds / 3600)
    let minutes = Math.floor((diffInSeconds - hours * 3600) / 60)
    let seconds = diffInSeconds % 60

    // 格式化输出
    let stringDay = String((day %= 24)).padStart(2, '0')
    let stringHours = String((hours %= 24)).padStart(2, '0')
    let stringMinutes = String(minutes).padStart(2, '0')
    let stringSeconds = String(seconds).padStart(2, '0')

    // console.log(`${stringDay}天${stringHours}:${stringMinutes}:${stringSeconds}`)
    countdown.value = `${stringDay}天${stringHours}:${stringMinutes}:${stringSeconds}`

    // 每秒递减
    diffInSeconds--
    timerId = setTimeout(updateCountdown, 1000)
  }

  // 启动倒计时
  updateCountdown()
}

// 停止倒计时
const stopCountdown = () => {
  clearInterval(timerId)
  timerId = null
}

// 组件挂载后初始化
onMounted(() => {
  // console.log(`当前时间：`, props.nowTime)

  startCountdown(props.nowTime, props.endTime)
})

// 组件卸载前清理
onBeforeUnmount(() => {
  stopCountdown()
})
</script>
<style scoped lang="scss">
.chat-countdown-timer {
  display: flex;
  justify-content: space-between;
  width: 100%;
  line-height: 38rpx;
  padding: 15rpx 30rpx;
  font-weight: 500;
  font-size: 24rpx;
  color: var(--fontColor);
  background: var(--bgColor);
  box-sizing: border-box;

  .dot {
    display: flex;
    align-items: center;
  }

  .dot::before {
    display: block;
    content: '';
    width: 13rpx;
    height: 13rpx;
    margin-right: 10rpx;
    background: var(--fontColor);
    border-radius: 50%;
  }
}
</style>
